<?php
/* 
    Name：FastPHP
    CopyRight: Mr.Fu 2019SR0832915
*/
namespace app\extend\weixin;
/*
	微信自动登录接口插件
*/
use \app\base\Common;
use \app\extend\weixin\Wxcommon;

class Wxauth extends Common
{
	//微信认证URL
	private $Host="https://open.weixin.qq.com/connect/oauth2/authorize?";
	private $Response_type="code";	//private $Scope="snsapi_base";
  	private $Scope="snsapi_userinfo";
	private $State="1";
	private $Appid="";
	private $Appsecret="";
	private $Redirect_uri="";//回调地址
	private $Auth_url="";
	
	protected function _initialize()
	{
    	//执行父类的构造方法
    	parent::_initialize();
    	//读取微信登录配置
	 	$this->Host			=$this->Config['wxauth_url'];
	 	$this->Redirect_uri	=urlencode($this->Config['wx_redirect_url']);
	 	$this->Appid		=$this->Config['wx_appid'];
	 	$this->Appsecret	=$this->Config['wx_appsecret'];
		$this->Auth_url     =$this->Host."appid=".$this->Appid."&redirect_uri=".$this->Redirect_uri."&response_type=".$this->Response_type."&scope=".$this->Scope."&state=".$this->State."#wechat_redirect";
		
	}
	//返回微信登录请求URL
	public function GetLoginUrl()
	{
       return $this->Auth_url;
	}
	//立即跳转微信登录
	public function Login()
	{
		J($this->Auth_url);
	}
	//微信认证后的回调处理
	public function Auth()
	{
		$code=input('code');
		if($code==""){
			$this->error('微信登录回调失败',url('index/login'));
		}
		$url='https://api.weixin.qq.com/sns/oauth2/access_token?appid=';
        $access_token=file_get_contents($url.$this->Appid."&secret=".$this->Appsecret."&code=".$code."&grant_type=authorization_code");
        $access_token=json_decode($access_token,true);
        WLog('wxlogin',serialize($access_token));
        if(!isset($access_token['access_token'])){
           $this->error('微信登录回调失败',url('index/login'));
           exit();
        }
		$url='https://api.weixin.qq.com/sns/userinfo?access_token=';
		$wxuserinfo=file_get_contents($url.$access_token['access_token']."&openid=".$access_token['openid']);
		$wxuserinfo=json_decode($wxuserinfo,true);
      	$userinfo=db('member')->where('wxopenid',$wxuserinfo['openid'])->find();
      	//微信用户是否存在
      	if(is_array($userinfo) and $wxuserinfo['openid']!=""){
          	if($this->login_status($userinfo['id'])){
              	$this->Log_Write($userinfo['id'],$userinfo['username'],2,$userinfo['username'].'微信登录成功',0);
            	J('/');
            }else{
              	$this->Log_Write($userinfo['id'],$userinfo['username'],2,$userinfo['username'].'微信登录失败',1);
            	$this->error('微信登录失败！','/');
            }
        }else{
            //不存在直接注册微信会员
            $wxusername="WX_".GetRandStr(18);
            $wxuserpwd=GetRandStr(10);
            $facepic_data=file_get_contents($wxuserinfo['headimgurl']);
            $DIR1="/uploads/facepic/".MyDate('Ymd',time())."/";
            $FILENAME=time().GetRandStr(10).".jpg";
            $path=ROOT_PATH.$DIR1;
            if(!file_exists($path)){
                mkdir($path);
            }
            file_put_contents($path.$FILENAME,$facepic_data);
            $ip=GetIP();
            $time=time();
            $safecode=GetRandStr(16);
			$password=Encrypt($safecode,$wxuserpwd);
            $data=array(
              	'group'=>1,
                'username'=>$wxusername,
                'nickname'=>$wxuserinfo['nickname'],
                'password'=>$password,
                'safecode'=>$safecode,
                'wxopenid'=>$wxuserinfo['openid'],
                'facepic'=>$DIR1.$FILENAME,
                'balance'=>0,
                'integral'=>0,
                'type'=>'wx',
                'regtime'=>$time,
                'regip'=>$ip,
                'logintime'=>$time,
                'loginip'=>$ip,
                'status'=>0
            );
            $uid=db('member')->insertGetId($data);
          	if($this->LoginStatus($uid)){
              	$this->Log_Write($uid,$wxusername,2,$wxusername.'微信注册登录成功',0);
            	J('/');
            }else{
              	$this->Log_Write($uid,$wxusername,2,$wxusername.'微信注册登录失败',1);
            	$this->error('微信注册登录失败！','/');
            }
        }
	}
  	public function LoginStatus($id)
    {
    	$userinfo=db('member')->where('id',$id)->find();
      	if(is_array($userinfo) and $id>=1){
            $ip=GetIP();
            $time=time();
         	//开始登录
         	 $login_data=array(
              'id'=>$userinfo['id'],
              'username'=>$userinfo['username'],
              'nickname'=>$userinfo['nickname'],
              'logintime'=>$time,
              'loginip'=>$ip
          	);
         	$update=array('logintime'=>$time,'loginip'=>$ip);
            //记录登录时间和IP地址
            db('member')->where('username',$userinfo['username'])->update($update);   
            //加密管理登录信息数据
            $ciphertext=AuthCode(serialize($login_data),'ENCODE',$this->Config['cookie_secretkey']);
            //把密文存储到会话中
            session('userinfo',$ciphertext);
            return true;
        }else{
          	return false;
        }
    }
}
?>